package com.itheima.reflect.myreflect3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class ReflectDemo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        //method1();
        //method2();
        //method3();
        // 获取一个私有构造方法,并创建对象
        // 1.获取class对象
        Class<?> clazz = Class.forName("com.itheima.reflect.myreflect3.Student");
        // 2.获取私有构造方法
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class);
        // 被 private 修饰的成员,不能直接使用
        // 如果用反射强行获取并使用,需要临时取消访问检查
        constructor.setAccessible(true);
        // 3. 创建对象
        Student student = (Student) constructor.newInstance("zhangsan");
        System.out.println(student);
    }

    private static void method3() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        // 简写格式
        // 1.获取class对象
        Class<?> clazz = Class.forName("com.itheima.reflect.myreflect3.Student");
        // 2.在class类中有一个newInstance的方法,可以利用空参直接创建对象
        Student student = (Student) clazz.newInstance();
        System.out.println(student);
    }

    private static void method2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 1.获取class对象
        Class<?> clazz = Class.forName("com.itheima.reflect.myreflect3.Student");
        // 2.获取构造方法对象
        Constructor<?> constructor = clazz.getConstructor();
        // 3. 利用 newInstance 方法创建 Student 对象
        Student student = (Student) constructor.newInstance();
        System.out.println(student);
    }

    private static void method1() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 1.获取class对象
        Class<?> clazz = Class.forName("com.itheima.reflect.myreflect3.Student");
        // 2.获取构造方法对象
        Constructor<?> constructor = clazz.getConstructor(String.class, int.class);
        // 3. 利用 newInstance 方法创建 Student 对象
        Student student = (Student) constructor.newInstance("zhangsan", 23);
        System.out.println(student);
    }
}
